package com.yang.studentsapp.model;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.yang.studentsapp.EaseUser;
import com.yang.studentsapp.bean.InviteMessgeDao;
import com.yang.studentsapp.bean.UserDao;
import com.yang.studentsapp.ui.MyAppliction;
import com.yang.studentsapp.utils.WorkFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ${Ян-Вэнь-Чао} on 2016/10/19.
 */
public class ModleContact {
    UserDao userDao;
    InviteMessgeDao inviteMessgeDao;
    private Handler handler = new Handler(Looper.getMainLooper());

    public void addContact(final String name, String addReason, final IActionSend iActionSend) {
        iActionSend.start("正在发送好友请求");
        if (TextUtils.isEmpty(addReason)) {
            addReason = "加个好友呗";
        }
        final String finalAddReason = addReason;
        WorkFactory.instance().service().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().contactManager().addContact(name, finalAddReason);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            iActionSend.succes("好友请求成功，等待对方验证");
                        }
                    });
                } catch (final HyphenateException e) {
                    e.printStackTrace();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            iActionSend.error("请求添加好友失败" + e.getMessage());

                        }
                    });
                }
            }
        });
    }

    public void initUserDao() {
        if (userDao == null) {
            userDao = new UserDao(MyAppliction.getContext());
        }
    }

    public void addContactAdded(final String newContactName) {
        initUserDao();
        WorkFactory.instance().service().submit(new Runnable() {
            @Override
            public void run() {
                Map<String, EaseUser> localUsers = MyAppliction.getInstance().getContactList();
                Map<String, EaseUser> toAddUsers = new HashMap<String, EaseUser>();
                EaseUser user = new EaseUser(newContactName);
                if (!localUsers.containsKey(newContactName)) {
                    userDao.saveContact(user);
                }
                toAddUsers.put(newContactName, user);
                localUsers.putAll(toAddUsers);
            }
        });
    }


}
